<template>
  <a-card class="quota fixed z-50 bottom-0 right-0" :class="{ 'sider-breakpoint': siderBreakpoint }">
    <div class="quota-wrapper">
      <div>
        <span class="quota-desc">
          <span class="quota-selected">
            <slot />
          </span>
          <template v-if="currentPackage.id === 26 || currentPackage.id === 31">
            /已选：PC总热度<span class="quota-selected">{{ pcHeat }}</span> / 移动总热度<span class="quota-selected">{{
              wapHeat
            }}</span>
          </template>
          <template v-else>
            /已选总热度
            <span class="quota-selected">{{ totalHeatRate }}</span>
          </template>
        </span>
        <a-button
          type="primary"
          size="large"
          class="ml-5 quota__submit-btn"
          :danger="shouldDisabledSubmit"
          :loading="submitting"
          :disabled="false"
          @click="handleBeforeSubmit"
        >
          {{ submitBtnText }}
        </a-button>
      </div>
    </div>
  </a-card>
</template>

<script lang="ts" setup>
import { computed, toRefs, watch } from 'vue'
import { isNil } from 'lodash-es'
import { message } from 'ant-design-vue'
import type { PackageData } from '@/services/price-sheet/getPackageList'
import type { PriceKeyword } from '@/core/interfaces/keyword'
import { useMainStore } from '@/store/useMainStore'
import { storeToRefs } from 'pinia'
import { useRoute } from 'vue-router'

const mainStore = useMainStore()
// 获取对应的路由

const route = useRoute()

interface Emits {
  (e: 'submit'): void
  (e: 'before-submit'): void
}
// console.log(PackageData, 'PackageData');

interface Props {
  currentPackage: any
  selectedTableData: PriceKeyword[]
  submitting: boolean
  price: Number
}
defineOptions({
  name: 'CbFooter'
})

const emit = defineEmits<Emits>()

// 现在你可以通过 mainStore 来访问 bansdsx
// console.log(mainStore.bansdsx); // 输出 bansdsx 的值
// const bansdsxs = ref(mainStore.bansdsx)
// // const code = localStorage.getItem('code')
// const { bansdsx } = mainStore

// 监听mainStore.bansdsx
// watch(
//   () => code.value,
//   (newValue, oldValue) => {
//     code.value = localStorage.getItem('code')
//   }
// )

const { siderBreakpoint } = storeToRefs(mainStore)

const props = withDefaults(defineProps<Props>(), {
  currentPackage: () => ({}),
  selectedTableData: () => [],
  submitting: false
})
const { currentPackage, selectedTableData } = toRefs(props)

const shouldDisabledSubmit = computed(() => {
  if (currentPackage.value?.wordsNumTotal) {
    return selectedTableData.value.length > currentPackage.value.wordsNumTotal
  }
  return false
})

const numOfAdditions = computed(() => {
  if (isNil(currentPackage.value?.wordsNumTotal)) {
    return selectedTableData.value.length
  } else {
    return currentPackage.value.wordsNumTotal - selectedTableData.value.length
  }
})

const submitBtnText = computed(() => {
  if (selectedTableData.value.length === 0) {
    return '请选择词组'
  } else {
    return '提交审核'
  }
})

async function handleBeforeSubmit() {
  if (selectedTableData.value.length === 0) {
    message.error(`请最少选择1个词`)
    return
  }
  if (!checkClientTypeMatch() && !submitBtnHandler()) {
    emit('submit')
  }
}
const submitBtnHandler = () => {
  const { id, pcHeatLimit, wapHeatLimit } = currentPackage.value

  let maxHeat
  //校验热度是否超过
  if (id === 24 || id === 29 || id === 27 || id === 32) {
    maxHeat = pcHeatLimit
  }
  //移动端
  if (id === 25 || id === 30 || id === 28 || id === 33) {
    maxHeat = wapHeatLimit
  }
  if (totalHeatRate.value > maxHeat) {
    message.error('超出当前套餐最大热度')
    return true
  }

  //双端
  if (id === 26 || id === 31) {
    if (isPcHeatExceeded() || isWapHeatExceeded()) {
      message.error('超出当前套餐最大热度')
      return true
    }
  }
  return false
}

const totalHeatRate = computed(() => {
  return props.selectedTableData.reduce((sum, item) => sum + Number(item.heatRate || 0), 0)
})

// 计算 PC 和 WAP 的当前热度
const pcHeat = computed(() => {
  return props.selectedTableData
    .filter((item) => item.clientType === 0)
    .reduce((sum, item) => sum + (item.heatRate || 0), 0)
})

const wapHeat = computed(() => {
  return props.selectedTableData
    .filter((item) => item.clientType === 1)
    .reduce((sum, item) => sum + (item.heatRate || 0), 0)
})

// 校验 PC 热度是否超限
const isPcHeatExceeded = () => {
  if (!props.currentPackage || (props.currentPackage.id !== 26 && props.currentPackage.id !== 31)) return false
  return pcHeat.value > (props.currentPackage.pcHeatLimit || 0)
}

// 校验 WAP 热度是否超限
const isWapHeatExceeded = () => {
  if (!props.currentPackage || (props.currentPackage.id !== 26 && props.currentPackage.id !== 31)) return false
  return wapHeat.value > (props.currentPackage.wapHeatLimit || 0)
}

// 计算是否有类型不匹配的词
const hasMismatchedWords = computed(() => {
  const packageType = props.currentPackage.clientType // 0 或 1
  return props.selectedTableData.some((item) => item.clientType !== packageType)
})

// 校验并提示类型错误
const checkClientTypeMatch = () => {
  const { id } = currentPackage.value
  if (hasMismatchedWords.value && id !== 26 && id !== 31) {
    const expectedType = props.currentPackage.clientType === 0 ? 'PC' : '手机'
    message.error(`词选择错误：当前套餐仅支持${expectedType}端类型词`)
    return true
  }
  return false
}
</script>

<style lang="scss" scoped>
.quota {
  height: 85px;
  left: 208px;
  padding-right: 38px;
  transition: left 0.2s ease;

  ::v-deep(.ant-card-body) {
    padding: 0;
  }

  &-wrapper {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 5px;
  }

  &-desc {
    font-size: 16px;
  }

  &-selected {
    vertical-align: sub;
    font-size: 48px;
    font-weight: bold;
    color: #ff4d4f;
  }

  &__submit-btn {
    height: 56px;
    min-width: 134px;
    border-radius: 4px;
    font-size: 20px;
  }
}

.sider-breakpoint {
  left: 48px;
}
</style>
